package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.behavior.dto.ArticleInfoDtoV2;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.LikesBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApLikesBehavior;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApLikesBehaviorService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP点赞行为表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-19
 */
@Service
public class ApLikesBehaviorServiceImpl extends ServiceImpl<ApLikesBehaviorMapper, ApLikesBehavior> implements IApLikesBehaviorService {
    @Autowired
    private IApBehaviorEntryService entryService;

    @Override
    public ResponseResult likesBehavior(LikesBehaviorDto dto) {

        EntryDto entryDto = new EntryDto();
        entryDto.setUserId(AppThreadLocalUtil.get().getUserId());
        entryDto.setEquipmentId(dto.getEquipmentId());
        ApBehaviorEntry entry = entryService.getEntry(entryDto);
        dto.setEntryId(entry.getId());
        //找出对应行为id对应的行为表
        LambdaQueryWrapper<ApLikesBehavior> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApLikesBehavior::getEntryId, dto.getEntryId()).eq(ApLikesBehavior::getArticleId, dto.getArticleId()).eq(ApLikesBehavior::getType, dto.getType());
        ApLikesBehavior apLikesBehavior = getOne(queryWrapper);
        if (apLikesBehavior == null)
            apLikesBehavior = new ApLikesBehavior();
        BeanUtils.copyProperties(dto, apLikesBehavior);
        if (apLikesBehavior.getId() == null)
            apLikesBehavior.setCreatedTime(new Date());
        saveOrUpdate(apLikesBehavior);
        return ResponseResult.okResult();


    }

    @Override
    public boolean isLike(ArticleInfoDtoV2 dto) {
        Integer entryId;
        entryId=dto.getEntryId();
        LambdaQueryWrapper<ApLikesBehavior> queryWrapper = new LambdaQueryWrapper<>();
        //找出类型为文章的对应的行为表
        queryWrapper.eq(ApLikesBehavior::getEntryId, entryId).eq(ApLikesBehavior::getArticleId, dto.getArticleId()).eq(ApLikesBehavior::getType, 0);
        ApLikesBehavior apLikesBehavior = getOne(queryWrapper);
        //0为喜欢，1为取消喜欢
        return apLikesBehavior!=null&&apLikesBehavior.getOperation() == 0;

    }
}
